package com.data.modules.message.job;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.data.modules.message.entity.SysMessage;
import com.data.modules.message.handle.ISendMsgHandle;
import com.data.modules.message.handle.enums.SendMsgStatusEnum;
import com.data.modules.message.handle.enums.SendMsgTypeEnum;
import com.data.modules.message.service.ISysMessageService;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * 发送 自动部署消息任务
 */
@SuppressWarnings("ALL")
@Slf4j
public class SendCDJob implements Job {
    @Autowired
    private ISysMessageService messageService;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        // 1.读取消息中心数据，只查询未发送的
        //TODO 考虑避免不要短时间重复发版的情况
        List<SysMessage> list = (List<SysMessage>) messageService.lambdaQuery()
                .eq(SysMessage::getEsType, SendMsgTypeEnum.CD.getType())
                .in(SysMessage::getEsSendStatus, SendMsgStatusEnum.WAIT.getCode())
                .lt(SysMessage::getEsSendNum, 5)
                .orderByAsc(SysMessage::getEsSendStatus);

        if (ObjectUtil.isEmpty(list)) {
            return;
        }

        list.forEach(msg->{
            LambdaUpdateWrapper<SysMessage> wrapper = new LambdaUpdateWrapper<>();
            Integer sendNum = msg.getEsSendNum();
            wrapper.set(SysMessage::getEsSendNum, ++sendNum);
            wrapper.eq(SysMessage::getId, msg.getId());
            wrapper.set(SysMessage::getEsSendStatus, SendMsgStatusEnum.SUCCESS.getCode());
            try{
                ISendMsgHandle sendMsgHandle = (ISendMsgHandle) Class.forName(SendMsgTypeEnum.CD.getImplClass()).newInstance();
                sendMsgHandle.sendMsg(msg.getId(), msg.getEsReceiver(), msg.getEsTitle(),
                        msg.getEsContent().toString());
            }catch (Exception e){
                log.error(e.getMessage(),e);
                String error = e.getMessage();
                if (error.length() > 200) {
                    error = error.substring(0, 200);
                }
                wrapper.set(SysMessage::getEsResult, error);
                wrapper.set(SysMessage::getEsSendStatus, SendMsgStatusEnum.FAIL.getCode());
            }

            try{
                // 发送结果回写到数据库
                messageService.update(wrapper);
                //等待30秒 确认远程命令已经执行完成
                Thread.sleep(30* 1000);
            }catch (Exception e){
                log.error(e.getMessage(),e);
            }
        });

    }


}
